<?php
namespace App\Http\Controllers\Manage\Member;

use App\Ext\Common\UploadImage;
use App\Http\Controllers\Manage\CommonController;
use App\Model\Member\Store;
use App\Model\Member\Member;

class StoreController extends CommonController
{
    /**
     *
     * 文章列表
     *
     * @return mixed
     */
    public function index()
    {
        $field = [
            'id' => 'ID',
            'title' => '商户名称',
            'tel' => '联系电话',
            'star' => '商家星级',
            'member_id' => '绑定会员ID'
        ];
        $viewData = [];
        $viewData['title'] = '商户管理';
        # 列表查询字段
        $viewData['field'] = $field;
        $viewData['range'] = [
            'star' => star()
        ];
        $viewData['option_title'] = [
            'plus' => [
                'title'=>'添加商户',
                'route' => route('manage.member.stores.resource.create')
            ]
        ];
        # 行表操作菜单
        $viewData['option_row'] = [
            'edit' => [
                'title'=>'编辑',
                'route'=>'manage.member.stores.resource.edit'
            ],
//            'trash' => [
//                'title'=>'删除',
//                'route'=>'manage:stores.destroy'
//            ],
            'bind' => [
                'title'=>'绑定会员',
                'load'=>'manage.member.stores.bind',
                'where' => [
                    ['name' => 'user_id', 'condition' => '=', 'value' => '0']
                ]
            ],
            'unbind' => [
                'title'=>'解绑会员',
                'route'=>'manage.member.stores.unbind',
                'where' => [
                    ['name' => 'user_id', 'condition' => '!=', 'value' => '0']
                ]
            ],
        ];
        # 页面模态对话框
        $viewData['option_modal'] = [
//            'trash' => [
//                'method' => 'DELETE',
//                'title' => '删除记录',
//                'msg' => '确定要删除文章吗'
//            ],
            'unbind' => [
                'method' => 'DELETE',
                'title' => '解除绑定',
                'msg' => '确定要解除绑定会员吗'
            ],
        ];
        # 列表数据
        $store = new Store;
        $viewData['list'] = $this->constraintSelect($store, $field);
        # 渲染视图
        return view('manage.table', $viewData);
    }

    /**
     * 删除品牌
     * @param $id
     * @return mixed
     */
    public function destroy($id)
    {
        $store = Store::find($id);
        if (!$store) {
            return redirect()->back()->with('error', '商户ID不存在!');
        }
        $member = Member::where('store_id', $store->id)->first();
        if ($member) {
            return redirect()->back()->with('error', '此商户绑定了会员ID(' . $member->id . ')，不能删除!');
        }
//        $store->delete();
        return redirect()->back()->with('success', '品牌删除成功!');
    }

    /**
     * 创建品牌页面
     * @return mixed
     */
    public function create()
    {
        $param = [
            'title' => [
                'type' => 'text',
                'col' => '3',
                'name' => '商户名称',
            ],
            'tel' => [
                'type' => 'number',
                'col' => '3',
                'name' => '联系电话'
            ],
            'qq' => [
                'type' => 'number',
                'col' => '3',
                'name' => 'qq在线'
            ],
            'star' => [
                'type' => 'select',
                'col' => '3',
                'name' => '商户星级',
                'range' => star()
            ],
            'integral' => [
                'type' => 'number',
                'col' => '3',
                'name' => '商户积分'
            ],
            'money' => [
                'type' => 'number',
                'col' => '3',
                'name' => '账户金额'
            ],
            'status' => [
                'type' => 'select',
                'col' => '3',
                'name' => '状态',
                'range' => disable()
            ],
            'adds' => [
                'type' => 'text',
                'col' => '12',
                'name' => '商户地址'
            ],
            'content' => [
                'name' => '详细介绍',
                'type' => 'editor',
                'col' => '12',
                'upload_image' => route('manage.member.stores.upload', ['id' => 0]),
            ],
            'logo' => [
                'type' => 'thumb',
                'col' => '3',
                'name' => 'Logo图片',
                'accept' => 'image',
                'ratio' => '1'
            ]
        ];
        $viewData = [];
        $viewData['title'] = '新建会员商户信息';
        $viewData['form'] = $this->form($param);
        $viewData['form_url'] = route('manage.member.stores.resource.store');
        $viewData['form_method'] = 'POST';
        $viewData['form_button'] = [
            'back' => [
                'name' => '返回列表',
                'type' => 'button',
                'route'=> route('manage.member.stores.resource.index')
            ],
            'reset' => [
                'name' => '重置',
                'type' => 'reset',
            ],
            'submit'=> [
                'name' => '提交',
                'type' => 'submit',
            ]
        ];
        return view('manage.form', $viewData);
    }

    /**
     * 创建品牌操作
     * @return mixed
     */
    public function store()
    {
        # 接受输入信息
        if (!$this->request->has('title')) {
            return redirect()->back()->with('warning', '请输入商户名称!');
        }
        if (!$this->request->has('tel')) {
            return redirect()->back()->with('warning', '请输入您的联系电话!');
        }
        $logo = null;
        if ($this->request->has('logo')) {
            $logo = $this->request->input('logo');
            $logo = $this->uploadBase64Image($logo, 'store_logo');
        }
        $store = new Store();
        $store->title = $this->request->input('title');
        $store->tel = $this->request->input('tel');
        $store->qq = $this->request->input('qq');
        $store->adds = $this->request->input('adds');
        $store->content = $this->request->input('content');
        $store->star = $this->request->input('star');
        $store->integral = $this->request->input('money');
        $store->money = $this->request->input('money');
        $store->status = $this->request->input('status');
        if ($logo != null) $store->logo = $logo;
        if ($store->save()) {
            return redirect()->route('manage.member.stores.resource.create')->with('success', '商户信息添加成功!'); # 更新成功后跳转到列表页
        }
        return redirect()->back()->with('error', '商户信息添加失败!');
    }

    /**
     * 修改品牌信息页面
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        # 查询记录数据
        $store = Store::find($id);
        $param = [
            'title' => [
                'type' => 'text',
                'col' => '3',
                'name' => '商户名称',
                'value' => $store->title,
            ],
            'tel' => [
                'type' => 'number',
                'col' => '3',
                'name' => '联系电话',
                'value' => $store->tel,
            ],
            'qq' => [
                'type' => 'number',
                'col' => '3',
                'name' => 'qq在线',
                'value' => $store->qq,
            ],
            'star' => [
                'type' => 'select',
                'col' => '3',
                'name' => '商户星级',
                'range' => star(),
                'value' => $store->star,
            ],
            'integral' => [
                'type' => 'number',
                'col' => '3',
                'name' => '商户积分',
                'value' => $store->integral,
            ],
            'money' => [
                'type' => 'number',
                'col' => '3',
                'name' => '账户金额',
                'value' => $store->money,
            ],
            'status' => [
                'type' => 'select',
                'col' => '3',
                'name' => '状态',
                'range' => disable(),
                'value' => $store->status
            ],
            'adds' => [
                'type' => 'text',
                'col' => '12',
                'name' => '商户地址',
                'value' => $store->adds,
            ],
            'content' => [
                'type' => 'editor',
                'col' => '12',
                'name' => '详细介绍',
                'upload_image' => route('manage.member.stores.upload', ['id' => $id]),
                'value' => $store->content,
            ],
            'logo' => [
                'type' => 'thumb',
                'col' => '2',
                'name' => 'Logo图片',
                'accept' => 'image',
                'ratio' => '1',
                'value' => $this->domain . $this->path['store_logo'] . $store->logo,
            ]
        ];
        $viewData = [];
        $viewData['title'] = '编辑会员商户信息';
        $viewData['form'] = $this->form($param);
        $viewData['form_url'] = route('manage.member.stores.resource.update', ['id' => $id]);
        $viewData['form_method'] = 'PUT';
        $viewData['form_button'] = [
            'back' => [
                'name' => '返回列表',
                'type' => 'button',
                'route'=> route('manage.member.stores.resource.index')
            ],
            'reset' => [
                'name' => '重置',
                'type' => 'reset',
            ],
            'submit'=> [
                'name' => '提交',
                'type' => 'submit',
            ]
        ];
        return view('manage.form', $viewData);
    }

    /**
     * 修改品牌信息操作
     * @param $id
     * @return mixed
     */
    public function update($id)
    {
        # 接受输入信息
        if (!$this->request->has('title')) {
            return redirect()->back()->with('warning', '请输入商户名称!');
        }
        if (!$this->request->has('tel')) {
            return redirect()->back()->with('warning', '请输入您的联系电话!');
        }
        $logo = null;
        if ($this->request->has('logo')) {
            $logo = $this->request->input('logo');
            $logo = $this->uploadBase64Image($logo, 'store_logo');
        }
        $store = Store::find($id);
        $store->title = $this->request->input('title');
        $store->tel = $this->request->input('tel');
        $store->qq = $this->request->input('qq');
        $store->adds = $this->request->input('adds');
        $store->content = $this->request->input('content');
        $store->star = $this->request->input('star');
        $store->integral = $this->request->input('money');
        $store->money = $this->request->input('money');
        $store->status = $this->request->input('status');
        if ($logo != null) $store->logo = $logo;
        if ($store->save()) {
            return redirect()->route('manage:stores.index')->with('success', '商户信息修改成功!'); # 更新成功后跳转到列表页
        }
        return redirect()->back()->with('error', '商户信息修改失败!');
    }

    /**
     *
     * 设置商户绑定会员ID表单页面
     *
     * @param $id
     * @return mixed
     */
    public function bind($id)
    {
        $bindMemberID = Store::getBind($id);
        # 查询记录数据
        $param = [
            'member' => [
                'name' => '会员ID',
                'type' => 'text',
                'col' => '12',
                'value' => $bindMemberID
            ],
        ];
        $viewData['form'] = $this->form($param);
        $viewData['form_title'] = '为商户绑定会员ID';
        $viewData['form_url'] = route('manage:stores.bind', ['id' => $id]);
        $viewData['form_method'] = 'PUT';
        $viewData['form_button'] = [
            'return' => [
                'name' => '取消',
                'type' => 'button',
            ],
            'return' => [
                'name' => '提交',
                'type' => 'submit'
            ],
        ];
        # 渲染视图
        return view('manage..lib.form', $viewData);
    }

    public function setBind($id)
    {
        if (!$this->request->has('member')) {
            return redirect()->back()->with('warning', '没有填写绑定的会员ID!');
        }
        $member = $this->request->input('member');
        if (Store::setBind($id, $member)) {
            return redirect()->back()->with('success', '绑定会员成功!');
        }
        return redirect()->back()->with('error', '绑定会员失败，绑定的会员ID可能不存在!');
    }

    public function unBind($id)
    {
        if (Store::unBind($id)) {
            return redirect()->back()->with('success', '解绑会员成功!');
        }
        return redirect()->back()->with('error', '解绑会员失败!');
    }



    /**
     *
     * 上传文章图片接口
     * 返回summernote编辑器的值
     *
     * @return mixed
     */
    public function upload($id)
    {
        $response = array();
        if (count($_FILES) < 1) {
            $response['state'] = '没有接受到上传的文件!';
            return response()->json($response);
        }
        $files = $this->request->file('image');
        $images = array();
        foreach ($files as $file) {
            # 原始文件名
            $originalName = $file->getClientOriginalName();
            # 新文件名
            $fileName = time() . substr(mt_rand(), 5);
            $fileName = $fileName . '.' . $file->getClientOriginalExtension();
            # 验证图片大小
            $sizeMax = formatBytes($file->getMaxFilesize());
            $sizeMax = floor($sizeMax);
            $fileSize = formatBytes($file->getClientSize());
            if ($fileSize > $sizeMax) {
                $response['state'] = '文件"' . $originalName . '"容量为' . $fileSize . 'MB，超过上传文件大小限制，文件上传的最大限制为' . $sizeMax . 'MB';
                return response()->json($response);
            }
            # 验证图片格式
            $image = new UploadImage();
            $mime = ['jpg','jpeg','png']; # 文件类型限制
            if (!$image->checkMime($file, $mime)) {
                $response['state'] = '上传的文件格式限制为"jpg,jpeg,png"';
                return response()->json($response);
            }

            # 保存文件对象
            $imageParam = [
                'max' => ['w' => 1024, 'watermark' => $this->filePath['water_mark']],
                'small' => ['w' => 24, 'h' => 24],
            ];
            $result = $image->save($file, $this->path['store_content'], $fileName, $imageParam);
            # 上传到云存储
            if ($result) $images[] = $result;
        }
        $response['state'] = 'SUCCESS';
        $response['file'] = $images;
        return response()->json($response);
    }
}